// ignore_for_file: use_build_context_synchronously

import 'dart:async';
import 'dart:convert';

import 'package:ali_auth/ali_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/models/login_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/http.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class AliAuthLoginTools {
  static late BuildContext context;
  static Timer? timer;

  static unit() {
    return ((View.of(context).physicalSize.height / View.of(context).devicePixelRatio * 0.65).floor() - 50) ~/ 10;
  }

  //全屏UI配置
  static final AliAuthModel _authConfig = AliAuthModel(
    Constant.ALIAUTHANDROIDKEY,
    Constant.ALIAUTHIOSKEY,
    isDebug: true,
    isDelay: false,
    switchCheck: false,
    pageType: PageType.fullPort,
    statusBarColor: "#FF8F36",
    bottomNavColor: "#FF8F36",
    isLightColor: false,
    isStatusBarHidden: false,
    statusBarUIFlag: UIFAG.systemUiFalgFullscreen,
    navColor: "#FF8F36",
    navText: "",
    navTextColor: "#ffffff",
    navReturnImgPath: "assets/auth_login/return_btn.png",
    navReturnImgWidth: 30,
    navReturnImgHeight: 30,
    navReturnHidden: false,
    navReturnScaleType: ScaleType.center,
    navHidden: false,
    logoOffsetY: unit() * 2,
    logoImgPath: "assets/auth_login/logo.png",
    logoHidden: false,
    logBtnText: "本机号码一键登录",
    logBtnTextSize: 30.sp.toInt(),
    logBtnTextColor: "#2A2A2A",
    protocolOneName: "《用户协议》",
    protocolOneURL: "https://fengshui.romko.top/home/user-agreement.html",
    protocolTwoName: "《隐私协议》",
    protocolTwoURL: "https://fengshui.romko.top/home/private-agreement.html",
    protocolOwnColor: '#C60000',
    protocolOwnOneColor: '#C60000',
    protocolOwnTwoColor: '#C60000',
    protocolLayoutGravity: Gravity.centerHorizntal,
    logBtnBackgroundPath:
    "assets/auth_login/login_btn_normal.png,assets/auth_login/login_btn_unable.png,assets/auth_login/login_btn_press.png",
    loadingImgPath: "authsdk_waiting_icon",
    logoOffsetY_B: -1,
    numberColor: "#2A2A2A",
    numberSize: 32.sp.toInt(),
    logoScaleType: ScaleType.fitXy,
    numFieldOffsetY: unit() * 7,
    numFieldOffsetY_B: -1,
    numberFieldOffsetX: 0,
    numberLayoutGravity: Gravity.centerHorizntal,
    logBtnOffsetY: unit() * 8,
    logBtnOffsetY_B: -1,
    logBtnWidth: 590.w.toInt(),
    logBtnHeight: 100.w.toInt(),
    logBtnOffsetX: 0,
    logBtnMarginLeftAndRight: 80.w.toInt(),
    logBtnLayoutGravity: Gravity.centerHorizntal,
    privacyOffsetX: -1,
    privacyOffsetY: -1,
    privacyOffsetY_B: 28,
    checkBoxWidth: 18,
    checkBoxHeight: 18,
    checkboxHidden: false,
    navTextSize: 18,
    logoWidth: 300.w.toInt(),
    logoHeight: 300.w.toInt(),
    switchAccTextSize: 28.sp.toInt(),
    switchAccText: "其他号码登录",
    switchOffsetY: unit() * 9 + 10,
    switchOffsetY_B: -1,
    switchAccHidden: false,
    switchAccTextColor: "#FFFFFF",
    sloganHidden: true,
    uncheckedImgPath: "assets/auth_login/btn_unchecked.png",
    checkedImgPath: "assets/auth_login/btn_checked.png",
    privacyState: false,
    protocolGravity: Gravity.centerHorizntal,
    privacyTextSize: 24.sp.toInt(),
    privacyMargin: 40,
    privacyBefore: "我已阅读并同意",
    privacyEnd: "",
    vendorPrivacyPrefix: "《",
    vendorPrivacySuffix: "》",
    dialogWidth: -1,
    dialogHeight: -1,
    dialogBottom: false,
    dialogOffsetX: 0,
    dialogOffsetY: 0,
    pageBackgroundPath: "assets/auth_login/background_image.jpg",
    webViewStatusBarColor: "#FFFFFF",
    webNavColor: "#FFFFFF",
    webNavTextColor: "#404040",
    webNavTextSize: 30.sp.toInt(),
    webNavReturnImgPath: "assets/auth_login/return_btn.png",
    webSupportedJavascript: true,
    authPageActIn: "in_activity",
    activityOut: "out_activity",
    authPageActOut: "in_activity",
    activityIn: "out_activity",
    screenOrientation: -1,
    logBtnToastHidden: false,
    dialogAlpha: 1.0,
    privacyOperatorIndex: 0,
    backgroundPath: "assets/auth_login/background_image.jpg",
  );

  //初始化
  static Future init(BuildContext ct) async {
    context = ct;
    AliAuth.loginListen(onEvent: (onEvent) {
      debugPrint("onEvent==$onEvent");
      timer?.cancel();
      timer = null;
      EasyLoading.dismiss();
      final code = int.parse(onEvent['code']);
      switch (code) {
        case 600000:
          loginWithoutCode(
            mounted: true,
            token: onEvent['data']
          );
          break;
        case 700002://点击登录按钮
          //如果返回data=null，说明可能没有勾选对话框
          if (onEvent['data'] == null || onEvent['data'] == '') {
            debugPrint('请先阅读用户协议');
          }
          break;
        case 700001://点击切换按钮，⽤户取消免密登录。
          if (onEvent['data'] != null) {
            // AliAuth.quitPage();
            Future.delayed(const Duration(milliseconds: 200), () {
              ct.push('/phone_code_login');
            });
          }
          break;
        case 600002:
        case 600004:
        case 600005:
        case 600007:
        case 600008:
        case 600009:
        case 600010:
        case 600011:
        case 600012:
        case 600013:
        case 600014:
        case 600015:
        case 600017:
        case 600021:
        case 600025:
        case 600026:
          context.push('/phone_code_login');
          break;
      }
    });
  }

  static Future login(BuildContext ct) async {
    /// 一键登陆 需要用try-catch[PlatformException]捕获插件返回的异常
    /// 无返回内容,调用之后，会在[handleEvent]的[onEvent]返回回调
    /// [timeout] 超时，单位秒
    try {
      AliAuth.quitPage();
      timer = Timer(const Duration(milliseconds: 500), () {
        EasyLoading.show(status: '加载中...');
      });
      AliAuth.initSdk(_authConfig);
      // AliAuth.login();
      // AliAuthClient.quitLoginPage();
      // AliAuthClient.loginWithConfig(authConfig: _authConfig);
    } catch(e) {
      rethrow;
    } finally {
      timer?.cancel();
      timer = null;
      EasyLoading.dismiss();
    }
  }

  static Future loginWithoutCode({required bool mounted, required String token}) async {
    try {
      final userProvider = context.read<UserProvider>();
      final data = await Fetch.request(Method.GET, '/user/onceLogin', params: {
        'token': token
      }, context: context);
      print('data==$data');
      final LoginModel result = LoginModel.fromJson(json.decode(data.data));
      userProvider.saveToken(result.data!.token.toString());
      userProvider.saveUserInfo(result.data!.user!);
      ///未注册
      if (result.data?.user?.username == null) {
        context.push('/register_nickname');
        return;
      }
      if (result.data?.user?.sex == null) {
        context.push('/register_sex');
        return;
      }
      if (result.data?.user?.birthday == null) {
        context.push('/register_birthday');
        return;
      }
      context.go('/');
    } catch(e) {
      rethrow;
    }
  }

}